import axios from 'axios'
import util from '@/utils/util'
import loading from '@/utils/loadingPlugin'
import qs from 'qs'
import {SecretKey, requestId, domainName} from '@/api/api_config.js'
import store from '@/store/index';
axios.defaults.timeout = 10000
//设置全局的请求次数，请求的间隙
axios.defaults.retry = 4
axios.defaults.retryDelay = 1000

let axios_setimeout;
function axios_instance(url, type) {
  let instance = axios.create({
    baseURL: url,
    headers: {
      'Content-Type': type.toString() === '0' ? 'application/x-www-form-urlencoded' : 'application/json',
      'requester': requestId,
    },
  })

  instance.interceptors.request.use(config => {
    config.headers.sign = util.createSign(config.data, SecretKey)
    console.log('config',config);
    if (type.toString() === '0') {
      config.data = qs.stringify(config.data)
    }
    if (store.getters.getUserId){
      config.headers.Authorization = store.getters.getAccessToken
        .replace(/(^\")|(\"$)/g, '')
    }
    if (config.showLoading) {
       loading.showFullScreenLoading()
    }
    return config
  }, err => {
    loading.tryHideFullScreenLoading()
    return Promise.reject(err)
  })
  instance.interceptors.response.use(response => {
    //业务随后再考虑下如何填充
    if (response.config.showLoading) {
      loading.tryHideFullScreenLoading()
    }   
    return response
  }, err => {
    store.dispatch('setNetworlk', true)
    loading.tryHideFullScreenLoading()
    return Promise.reject(err)
  })
  return instance
}

const axios_Instance = (type = 0) => axios_instance(`https://${domainName}/ticket/bus/`, type)
const sso_Instance  = (type = 0) => axios_instance(`https://${domainName}/sso/bus/`, type)
const pay_Instance  = (type = 0) => axios_instance(`https://${domainName}/pay/bus/`, type)

export {
  axios_Instance,
  sso_Instance,
  pay_Instance
}

